package com.jd.platform.gobrs.client.manager;

import com.jd.platform.gobrs.client.ApplicationContextProvider;
import com.jd.platform.gobrs.client.config.BootstrapProperties;
import com.jd.platform.gobrs.client.hcache.AbstractWrapper;
import com.jd.platform.gobrs.client.hcache.HCacheWrapper;
import com.jd.platform.gobrs.client.hcache.Wrapper;
import com.jd.platform.gobrs.common.exception.CacheHandlerNotFoundException;
import com.jd.platform.gobrs.common.exception.HCacheException;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @program: gobrs
 * @ClassName AbstractCacheManager
 * @description:
 * @author: sizegang
 * @create: 2022-01-09 00:12
 * @Version 1.0
 **/
@Slf4j
public abstract class AbstractCacheManager implements CacheManager {

    @Resource
    private BootstrapProperties bootstrapProperties;

    @Resource
    private ApplicationContextProvider applicationContextProvider;

    private Wrapper wrapper;

    @PostConstruct
    public void init() {
        try {
            wrapper = applicationContextProvider.getBean(Wrapper.class);
        } catch (Exception exception) {
        }
    }

    @Override
    public Object getCache(String key) {
        Object cacheValue = doGetCache(key);
        if (cacheValue != null) {
            return cacheValue;
        }
        // start hcache  The second level cache
        if (bootstrapProperties.ishCache()) {
            if (wrapper == null) {
                throw new HCacheException("hcache wrapper not impl");
            }
            Object value = wrapper.doGetValue(key);
            if (value != null) {
                setCache(key, value);
            }
            return value;
        }
        return null;
    }

    abstract Object doGetCache(String key);
}
